<template>
	<view class="contract">
		<view :style="{ height: navBarHeight + 'px' }" class="custom-nav-bar">
			<!-- <view class="nav-title">审查列表</view> -->
		</view>
		<view class="up-tabs-container" :style="{padding:`${navBarHeight}px 20rpx 0;` }">
			<view class="" style="margin-bottom: 30rpx;">
				<view class="">
					审查记录
				</view>
				<view class="gradient-line"></view>
			</view>
<!-- 			<uni-search-bar v-model="searchValue" radius="5" placeholder="自动显示隐藏" clearButton="auto" cancelButton="none"
				@confirm="search" @clear="clearSearch" /> -->
				<view class="topBtnBox">
					<view class="searchBox">
						<up-search v-model="searchValue" placeholder="搜索记录" @search="search" @custom="search" :show-action="false" @clear="clearSearch"></up-search>
					</view>
<!-- 					<view class="dateBox">
						<uni-datetime-picker type="date" v-model="single" @change="dateSearch()"><up-icon name="calendar" size="30"></up-icon></uni-datetime-picker>
					</view> -->
				</view>

		</view>
		<view class="page-content">
			<scroll-view class="content-main" scroll-y @scrolltolower="onScrollToLower" :style="{ height:`calc(100vh - ${navBarHeight}px);` ,padding:`${navBarHeight + 100}px 0 0 0;` }" enable-flex>
				<view class="main-list">
					<view v-for="(value, key) in aiTaskList" :key="key">
						<view class="main-box_text">
							<text>{{ strFormatMonth(key) }} {{ getWeekday(key) }}</text>
						</view>
						<view class="">
							<uni-swipe-action>
								<uni-swipe-action-item v-for="item in value" :key="item.taskId" :style="item.taskStatus != 0 ? '' : 'pointer-events: none;'" :right-options="rightOptions" @click="bindClick($event,item)">
									<view class="" @click="showDetail(item)">
										<view class="" style="display: flex;flex-direction: row;justify-content: space-between;align-items: center;">
											<view class="main-box_title">{{ item.taskType }} - {{item.taskNumber}}</view>
<!-- 											<view v-if="item.taskStatus == 0" class="flex-main" style="flex-shrink: 0;padding-left: 15px;">
												<view class="load-box">
													<view class="load-box_line"></view>
												</view>
												<view class="load-title">
													处理中
												</view>
											</view> -->
											<view class="flex-main" style="flex-shrink: 0;padding-left: 15px;" v-if="item.taskStatus == 0">
												<view class="load-title" style="color: #e6a23c">
													处理中
												</view>
											</view>
											<view class="flex-main" style="flex-shrink: 0;padding-left: 15px;" v-if="item.taskStatus == 1">
												<view class="load-title" style="color: #409EFF">
													排队中
												</view>
											</view>

											<view class="flex-main" style="flex-shrink: 0;padding-left: 15px;" v-if="item.taskStatus == 3">
												<view class="load-title" style="color: #fa3534">
													失败
												</view>
											</view>
										</view>
										<view class="line2">{{ item.taskContent}}</view>
									</view>
								</uni-swipe-action-item>
								<!-- </uni-swipe-action-item> -->
							</uni-swipe-action>
						</view>
					</view>
					<!-- 底部加载状态提示 -->
					<view v-if="aiTaskList.length!=0" class="loading-footer">
						<text v-if="noMore">没有更多了~</text>
						<text v-else-if="loading">加载中...</text>
					</view>
					<view v-else class="loading-footer_home">
						<image src="/static/noData.png" mode="aspectFit" style="width: 100%;">
						</image>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 输入框示例 -->
		<up-popup :show="inputDialog" mode="center"  @close="inputDialog = false" @open="inputDialog = true">
			<view class="dialog-rename">
				<view class="">
					<view class="dialog-rename-title">
						重命名
					</view>
					<view class="dialog-rename-input">
						<input v-model="newRecName" type="text" name="" id="" />
					</view>
				</view>
				<view class="flex-between-mian">
					<view class="dialog-rename_btn" @click="dialogInputClose">取消</view>
					<view class="dialog-rename_btn dialog-rename_btn__left" @click="dialogInputConfirm">保存</view>
				</view>
			</view>
		</up-popup>
			
		<up-popup :show="show" mode="center"  @close="show = false" @open="show = true">
			<view style="padding: 40rpx;">
				<text>是否删除当前合同分析成果？</text>
			</view>
			<view class="" style="display: flex;justify-content: space-around;padding-bottom: 40rpx;">
				<view class=""  @click="show = false"><u-button type="info" text="取消"></u-button></view>
				<view class=""  @click="deleteInfo"><u-button type="error" text="确定"></u-button></view>
			</view>
		</up-popup>
	</view>
</template>

<script setup>
	import { ref, getCurrentInstance, onMounted, onUnmounted, reactive } from 'vue';
	import { useAuthStore } from '@/store/index.js';
	import { getAiAskList,detContractTask } from '@/api/list.js';
	import { strFormatMonth, getWeekday } from '@/utils/format.js'
	import { getNewDateArr } from '@/utils/list.js'
	import { onShow } from '@dcloudio/uni-app'
	
	const navBarHeight = ref(0);
	const authStore = useAuthStore();
	const userId = ref(authStore.userId);
	const aiTaskList = ref([]);
	const queryParams = ref({
		pageNum: 1,
		pageSize: 8,
		userId: authStore.userId,
		taskNumber:''
	})
	const total = ref()
	// 新增状态变量
	const loading = ref(false)    // 加载中状态
	const noMore = ref(false)     // 数据全部加载完成标志
	const show = ref(false)
	
	const timer = ref(null);
	const dateshow = ref(false)
	const searchValue = ref('')
	const single = ref('')
	const taskId = ref('')
	
	const rightOptions = reactive([{
		text: '重命名',
		style: {
			backgroundColor: '#007aff',
			color: '#fff',
			height: '100%' // 与 main-box 的高度一致
		}
	}, {
		text: '删除',
		style: {
			backgroundColor: '#dd524d',
			color: '#fff',
			height: '100%' // 与 main-box 的高度一致
		}
	}])
	const inputDialog = ref(false)
	const newRecName = ref('')
	const suffixName = ref('')
	const userInfo = ref()
	
	const showDetail = (item) => {
		if(item.taskStatus == 2) {
			uni.navigateTo({
			    url: `/pages/index/index?taskId=${item.taskId}`
			});
		}
	}
	
	const toggleActive = (index) => {
		this.$set(this.list, index, {
		  ...this.list[index],
		  isActive: !this.list[index].isActive,
		});
	}
	/* 表格操作 */
	/** 查询ai任务列表 */
	const getList = async () => {
		if (loading.value || noMore.value) return
		// loading.value = true
		try {
		    const res = await getAiAskList(queryParams.value)
			queryParams.value.pageSize = 8
		    // 首屏加载
		    if (queryParams.value.pageNum === 1) {
				aiTaskList.value = res.data.rows
				res.data.rows.forEach((item,index) => {
				  if(item.taskStatus == 0) {
					  timer.value = setTimeout(() =>{
						  noMore.value = false
						  loading.value = false
						  uni.hideLoading()
						  queryParams.value.pageSize = queryParams.value.pageNum * queryParams.value.pageSize
						  queryParams.value.pageNum = 1
						getList()
					  }, 5000)
				  }
				})
		    } 
		    // 滚动加载更多
		    else { 
		      aiTaskList.value = [...aiTaskList.value, ...res.data.rows]
		    }
		
		    // 判断是否还有更多数据
		    if (aiTaskList.value.length >= res.data.total || res.data.rows.length < queryParams.value.pageSize) {
		      noMore.value = true
		    }
		    
		    // 页码递增（需要放在数据合并之后）
		    if (res.data.rows.length > 0) {
		      queryParams.value.pageNum++
		    }
		} catch (error) {} finally {}
		aiTaskList.value = getNewDateArr(aiTaskList.value)
	};
	
	const deleteInfo = async () => {
		const res = await detContractTask(taskId.value)
		if(res.data.code == 200){
			show.value = false
			uni.showToast({
			  title: '删除成功！'
			})
			noMore.value = false
			queryParams.value = {
				pageNum: 1,
				pageSize: queryParams.value.pageNum * queryParams.value.pageSize,
				userId: authStore.userId
			}
			await getList()
		}
	}
	
	// 滚动到底部触发
	const onScrollToLower = () => {
		if (!noMore.value) getList()
	}
	
	// 定义搜索方法，当 @confirm 事件触发时调用
	const search = async (e) => {
		queryParams.value.taskNumber = e
		queryParams.value.pageNum = 1
		noMore.value = false
		loading.value = false
		await getList()
	};
	
	const clearSearch = async () => {
		delete queryParams.value.taskNumber
		queryParams.value.pageNum = 1
		noMore.value = false
		loading.value = false
		await getList()
	}
	
	// const dateSearch = () => {
	// 	console.log(single.value)
	// }
	
	const bindClick = async (e, item) => {
		taskId.value = item.taskId
		if (e.index == 0) {
			if (item.taskNumber.includes('.')) {
				let parts = item.taskNumber.split('.'); // ["example", "com"]
				newRecName.value = parts[0]
				suffixName.value = parts[1]
			} else {
				newRecName.value = item.taskNumber
				suffixName.value = ''
			}
			await nextTick();
			inputDialog.value = true;
		} else {
			show.value = true
		}
	}
	
	onShow(async() => {
		try{
			queryParams.value.pageNum = 1 // 重置页码
			noMore.value = false
			loading.value = false
			if(authStore.userId != ''){
				await getList()
			}else{
				setTimeout(async()=>{
					userInfo.value = uni.getStorageSync('loginInfo').user
					queryParams.value.userId = uni.getStorageSync('loginInfo').user.userId
					await getList()
				},1000)
			}
		}catch {
			uni.redirectTo({
				url:'/pages/login/index'
			})
		}
	})
		
	onMounted(async ()=>{
		try {
		    const res = await uni.getSystemInfo();
		    // 获取状态栏高度（刘海高度）
		    const statusBarHeight = res.statusBarHeight;
		    // 标准导航栏高度，一般为 44px（iOS）或 48px（Android）
		    const defaultNavBarHeight = res.platform === 'ios' ? 44 : 48;
		    // 计算自定义导航栏的高度
		    navBarHeight.value = statusBarHeight + defaultNavBarHeight;
		} catch (error) {
		    console.error('获取设备信息失败:', error);
		}
		if(authStore.userId == '') {
			authStore.getInfoData()
		}
	});
</script>
<style>
	.u-tabbar-item {
		padding-top: 10px;
	}
	.u-page__item__slot-icon{
		width: 30px;
		height: 30px;
	}
	.button-group--right {
		right: -6rpx !important;
	}
</style>

<style>
	.contract {
		background-color: #f0f4f9;
		display: flex;
		flex-direction: column;
		background-color: #fff;
	}
	
	.custom-nav-bar {
		position: fixed;
		top: 0;
		width: 100vw;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #F2F3F5;
		z-index: 99;
	}
	
	.up-tabs-container {
		position: fixed;
		top: 30rpx;
		background-color: #f5f7fb;
		z-index: 1;
		font-size: 20px;
		padding: 0 20px;
		width: 100%;
		z-index: 999;
		height: unset;
		box-sizing: border-box;
	}

	.gradient-line {
		width: 30%;
		height: 10px;
		/* 线的高度 */
		background: linear-gradient(to right, #2979ff, transparent);
		border-radius: 10px 0 0 10px;
		margin-top: -3%;
	}
	.topBtnBox {
		display: flex;
		justify-content: space-around;
		gap: 15px;
		align-items: center;
		margin-bottom: 20rpx;
	}
	.searchBox {
		flex: 1;
	}
	.user-avatar {
		position: absolute;
		left: 15px;
		bottom: 10px;
		overflow: hidden;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: baseline;
	}
	
	.nav-title {
		font-size: 40rpx;
		font-weight: bold;
		text-align: center;
		position: absolute;
		bottom: 20rpx;
	}
	
	.user-avatar_item {
		margin-left: 2px;
		font-size: 20px;
		font-weight: 700;
	}
	
	.page-content {
		flex: 1;
	}
	
	.content-main {
		overflow-y: auto;
	}
	
	.main-list {
		height: 100%;
		padding: 20px;
	}
	
	.main-box {
		width: 100%; /* 固定宽度计算（减去间隙的一半） */
		min-width: 0; /* 防止内容溢出影响布局 */
		border-radius: 15px;
		/* border: 1px solid #ececec; */
		box-sizing: border-box;
		padding: 20px;
		/* 添加以下属性确保内容不会撑开盒子 */
		overflow: hidden;
		word-break: break-word; /* 长文本自动换行 */
		box-shadow: 0 0px 10px #666;
	}
	.warning {
		background-color: rgba(230, 162, 60, 0.3);
	}
	.primary {
		background-color: rgba(64, 158, 255, 0.3);
	}
	.success {
		background-color: rgba(103, 194, 58, 0.3);
	}
	.danger {
		background-color: rgba(250, 53, 52, 0.3);
	}
	.main-box_title{
	    display: -webkit-box; /* 关键属性 */
		-webkit-box-orient: vertical; /* 文字垂直排列 */
		-webkit-line-clamp: 2; /* 限制显示两行 */
		overflow: hidden;
		text-overflow: ellipsis;
		line-height: 1.5; /* 建议设置行高，避免文字重叠 */
		font-weight: 600;
		font-size: 20px;
	}
	
	.main-box_status {
		position: absolute;
		right: 0;
	}
	
	/* 新增底部加载提示样式 */
	.loading-footer {
		width: 100%;
		text-align: center;
		padding: 20rpx;
		color: #A8ABB2;
		font-size: 26rpx;
	}
	.line2 {
	    word-break: break-all;
	    display: -webkit-box;
	    -webkit-box-orient: vertical;
	    -webkit-line-clamp: 2;
	    overflow: hidden;
		font-size: 18rpx;
		margin-top: 10rpx;
		color: #303133;
	}
	.statusBar {
/* 		position: absolute;
		left: 0; */
		width: 120rpx;
		line-height: 50rpx;
		text-align: center;
	}
	.detBtn {
		box-sizing: border-box;
		width: 120rpx;
		border: 1px solid #F56C6C;
		color: #F56C6C;
		line-height: 50rpx;
		text-align: center;
		border-radius: 10rpx;
	}
	
	::v-deep .uni-swipe_text--center {
		width: 100%;
		min-width: 0;
		border-radius: 15px;
		border: 1px solid #ececec;
		box-sizing: border-box;
		padding: 20px 10px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
		overflow: hidden;
		word-break: break-word;
	}

	::v-deep .uni-swipe {
		margin-bottom: 20px;
	}

	::v-deep .uni-swipe_button-group>.uni-swipe_button:nth-child(2) {
		border-radius: 0 15px 15px 0;
	}

	::v-deep .uni-searchbar {
		padding: 10px 0;
	}
</style>